# coding:utf-8

import requests


class WeatherAndtime:
    def __init__(self, api_key):
        self.api_key = api_key

    # 获取天气信息
    def get_weather(self, city):
        # 获取城市id
        url = f"https://geoapi.qweather.com/v2/city/lookup?location={city}&{city}&key={self.api_key}"
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            city_id = data['location'][0]['id']
            # print(f'{city}的城市id是{city_id}')
        else:
            city_id = '101010100'

        url = f"https://devapi.qweather.com/v7/weather/3d?location={city_id}&key={self.api_key}"
        response = requests.get(url)
        if response.status_code == 200:
            data = response.json()
            result = f'以下为{city}近三天的天气：\n'
            for data in data['daily']:
                date = data['fxDate']  # 日期
                sunrise = data['sunrise']  # 日出时间
                temp_max = data['tempMax']  # 最高温度
                temp_min = data['tempMin']  # 最低温度
                text_day = data['textDay']  # 白天天气
                text_night = data['textNight']  # 夜晚天气
                wind_speed_day = data['windSpeedDay']  # 白天风速
                wind_speed_night = data['windSpeedNight']  # 夜晚风速
                windScaleDay = data["windScaleDay"]  # 白天风力等级
                windScaleN = data["windScaleNight"]
                wind_dir_day = data["windDirDay"]  # 白天风向
                wind_dir_night = data["windDirNight"]  # 夜晚风向
                humidity = data["humidity"]  # 湿度
                uv_index = data['uvIndex']  # 紫外线指数
                result += f"{date}：日出时间{sunrise}，最高{temp_max}摄氏度，最低{temp_min}摄氏度，白天天气是{text_day}，夜晚天气是{text_night}，白天风速{wind_speed_day}km/h，等级{windScaleDay}，风向：{wind_dir_day}，夜晚风速{wind_speed_night}km/h，等级{wind_dir_night}，风向：{wind_dir_night}，湿度{humidity}%，紫外线指数{uv_index}\n"

            return result
        else:
            return f'未获取到{city}实时天气,请按常规处理'


if __name__ == "__main__":
    weather_key = " " #和风天气（QWeather，官网：https://www.qweather.com）
    weatherandtime = WeatherAndtime(weather_key)
    print(weatherandtime.get_weather('上海'))
